package club.jdiy.admin.dao.impl;

import club.jdiy.core.base.JDiyBaseDao;
import club.jdiy.admin.entity.User;
import club.jdiy.core.ex.JDiyException;
import club.jdiy.utils.Md5Utils;

import javax.persistence.Query;
import java.util.List;

public class UserDaoImpl extends JDiyBaseDao<User, Integer> {

    public User changePwd(Integer userId, String oldPwd, String newPwd) {
        User po = findById(userId).orElseThrow(() -> new JDiyException("获取用户信息失败！"));
        if (!Md5Utils.validate(oldPwd, po.getPwd())) throw new JDiyException("原密码输入不正确！");
        po.setPwd(Md5Utils.encrypt(newPwd));
        return save(po);
    }

    public boolean hasRepeat(User user) {
        Query q = entityManager.createNamedQuery("User.hasRepeat");
        q.setParameter(1, user.getId());
        q.setParameter(2, user.getUid());
        List<?> ls = q.getResultList();
        return ls != null && ls.size() > 0;
    }
}
